#pragma once
#include <iostream>
#include "Log.hpp"
#include "InetAddr.hpp"
#include"Comman.hpp"
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <sys/socket.h> // 主要套接字函数和结构体（如 socket()）
#include <netinet/in.h> // 定义 sockaddr_in 和 IP 协议相关常量（如 INADDR_ANY）
#include <arpa/inet.h>  // 提供地址转换函数（如 inet_pton()）
#include <pthread.h>
#include <functional>
#include <memory>
namespace socket_ns
{
    class Socket;
    // 智能指针
    using SockSPtr = std::shared_ptr<Socket>;
   
    class Socket
    {
    public:
        // 纯虚函数，子类必须实现
        virtual void CreatSocketOrDie() = 0;
        virtual void BindSocketOrDie(uint16_t port) = 0;
        virtual void ListenSocketOrDie() = 0;
        virtual int Acceptor(InetAddr *clientaddr,int* code) = 0;
        virtual bool Connector(const std::string& peerip,uint16_t peerport) = 0;
        virtual void Close() = 0;
        virtual int Sockfd() = 0;
        virtual int Rev(std::string* out) = 0;
        virtual int Send(std::string& in) = 0;
        virtual ~Socket() = default;

    public:
    
        void BuildListenSocket(uint16_t port)
        {
            CreatSocketOrDie();
            BindSocketOrDie(port);
            ListenSocketOrDie();
        }
        bool BuildClientSocket(const std::string& peerip,uint16_t peerport)
        {
            CreatSocketOrDie();
            return Connector(peerip,peerport);

        }
    };
    class TcpSocket : public Socket
    {
    public:
        TcpSocket() {}
        TcpSocket(int sockfd) : _sockfd(sockfd)
        {
        }
        ~TcpSocket()
        {

        }
        void CreatSocketOrDie() override
        {
            // 创建套接字
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket error\n");
                exit(SOCKERROR);
            }
            SetNonBlock(_sockfd);
            //LOG(INFO, "listenSockfd:%d\n", _sockfd);
        }
        void BindSocketOrDie(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port);       // 主机字节序转换为网络字节序
            local.sin_addr.s_addr = INADDR_ANY; // 任意IP
            if (bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(BINDERROR);
            }
            //LOG(INFO, "bind success,port:%d\n", port);
        }
        void ListenSocketOrDie() override
        {
            if (listen(_sockfd, 5) < 0)
            {
                LOG(FATAL, "listen error\n");
                exit(LISTENERROR);
            }
            //LOG(INFO, "listen success,listenSockfd:%d\n", _sockfd);
        }
        // 需要获取远端的信息和文件IO的描述符
        int Acceptor(InetAddr *clientaddr,int* code) override
        {
            // 创建新的套接字
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 接受连接
            int sock = accept(_sockfd, (struct sockaddr *)&client, &len);
            *code = errno;//设置错误码
            if (sock < 0)
            {
                LOG(FATAL, "accept error,errno:%d\n",errno);
                //exit(ACCEPTERROR);
            }
            *clientaddr = InetAddr(client);
            SetNonBlock(sock);
           // LOG(INFO, "accept success\n");
           // return std::make_shared<TcpSocket>(sock); // 返回一个TcpSocket对象指针
           return sock;
        }
        bool Connector(const std::string& peerip,uint16_t peerport)
        {
            // 连接服务器
            sockaddr_in server;
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            server.sin_addr.s_addr = inet_addr(peerip.c_str());
            if (connect(_sockfd, (sockaddr *)&server, sizeof(server)) < 0)
            {
                LOG(FATAL, "connect error");
                return false;
            }
            LOG(INFO, "connect success");
            return true;
        }
        int Sockfd()
        {
            return _sockfd;
        }
        void Close()
        {
            ::close(_sockfd);
        }
        int Rev(std::string* out) override
        {
            char buffer[4096];
            int n = ::recv(_sockfd,buffer,sizeof(buffer),0);
            if(n < 0)
            {
                LOG(FATAL,"recv error");
                return -1;
            }
            buffer[n] = 0;
            *out += buffer;
            return n;
        }
        int Send(std::string& in) override
        {
            return ::send(_sockfd,in.c_str(),in.size(),0); 
        }
    private:
        int _sockfd;
    };
}